package com.briup.cms.web.Interceptor;

import com.briup.cms.exception.LoginException;
import com.briup.cms.utils.ExLogid;
import com.briup.cms.utils.JwtUtil;
import com.briup.cms.utils.MessageStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class LogInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(!(handler instanceof HandlerMethod)){
            return  true;
        }

        String token = request.getHeader("Authorization");
        if(token == null){
            throw new LoginException(MessageStatus.USER_TOKEN_NOT_EXIST);
        }
        try {
            JwtUtil.checkSign(token);
        } catch (Exception e) {
            throw new LoginException(MessageStatus.USER_TOKEN_INVALID);
        }
        String username = JwtUtil.getUserId(token);
        System.out.println(username);
        Map<String, Object> info = JwtUtil.getInfo(token);
        System.out.println("....LoginInterceptor"+info);
        HashMap<String, Object> map = new HashMap<>();
        map.put("username",username);
        map.put("realname",info.get("realname"));
        String uri = request.getRequestURI();
        String method = request.getMethod();
        map.put("uri",uri);
        map.put("method",method);
        ExLogid.setThreadLocal(map);
        return true;
    }
}
